-module(tester).

%-include("../../../ect/config.hrl").
%-define(ECT_UPGRADE_MODE,mode1).

-export([run/0, do_test_sh/0]).

mode2_proxy_cleanup(M, Version) ->
    ProxName = atom_to_list(M)++"_proxy"++integer_to_list(Version),
    Prox = list_to_atom(ProxName),
    %io:format("kill proxy ~p~n", [Prox]),
    code:purge(Prox), code:delete(Prox), code:purge(Prox),
    file:delete(ProxName++".beam").

mode2_total_cleanup() ->
    mode2_proxy_cleanup(alpha, 1),
    mode2_proxy_cleanup(beta, 1),
    mode2_proxy_cleanup(gamma, 1),
    mode2_proxy_cleanup(alpha, 2),
    mode2_proxy_cleanup(beta, 2),
    mode2_proxy_cleanup(gamma, 2).

reset_scenario() ->
    mode2_total_cleanup(),
    my_load_module(alpha, 1),
    my_load_module(beta, 1),
    my_load_module(gamma, 1).

switch_to_alpha2() ->
    mode2_proxy_cleanup(alpha, 1),
    mode2_proxy_cleanup(beta, 1),
    mode2_proxy_cleanup(gamma, 1),
    my_load_module(alpha, 2).

my_load_module(Module, Version) ->
    Name = atom_to_list(Module),
    V = integer_to_list(Version),
    file:copy(Name++"_v"++V++".erl", Name++".erl"),
    compile:file(Module, [{d,'ECT_UPGRADE_MODE',?ECT_UPGRADE_MODE},report,verbose]),
    ImplModule = list_to_atom(Name++"_impl"++V),
    code:purge(ImplModule), code:delete(ImplModule),
    ect:load(ImplModule, ?ECT_UPGRADE_MODE).
    %io:format("switched to ~p_v~p~n", [Module, Version]).

run() ->
    reset_scenario(),
    
    compile:file(tuser),
    code:purge(tuser), code:delete(tuser), code:purge(tuser),

    io:format("Test set #1 (fields): ", []),
    Status1 = tuser:test_alpha(1, none),
    switch_to_alpha2(),
    mode2_proxy_cleanup(alpha, 1), my_load_module(alpha, 2),
    ok = tuser:test_alpha(2, Status1),
    
    io:format("okay~nTest set #2 (fields): ", []),
    reset_scenario(),
    BStatus1 = tuser:test_abeta(1, none),
    switch_to_alpha2(),
    ok = tuser:test_abeta(2, BStatus1),

    io:format("okay~nTest set #3 (supercalls): ", []),
    reset_scenario(),
    S3_1 = tuser:test_scall(1, none),
    switch_to_alpha2(),
    ok = tuser:test_scall(2, S3_1),
    
    io:format("okay~nTest set #4 (new/propagate): ", []),
    reset_scenario(),
    S4_1 = tuser:test_new(1, none),
    switch_to_alpha2(),
    ok = tuser:test_new(2, S4_1),
    
    io:format("okay~n", []).
    
do_test_sh() ->
    run(),
    io:format("HCS EXTRA TEST: COMPLETED~n", []),
    erlang:halt().